Vue.component('upload-images', {
    template: `<el-upload class="upload-demo" :show-file-list="false" accept="image/*" drag :on-change="upload" :auto-upload="false" action="" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
            只能上传jpg/png文件，且不超过500kb
            <el-slider style="width:350px" :min="1" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
        </div>
    </el-upload>
    `,
    props: ['data'],
    data() {
        return {
            quality: 100,
        }
    },
    methods: {
        formatTooltip(val) {
            return '图片压缩比例：' + val + '%';
        },
        upload({ raw }) {
            const that = this;
            new Compressor(raw, {
                quality: that.quality / 100,
                success(file) {
                    const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
                    const isLt500K = file.size / 1024 / 1024 < 0.5; // 500KB  
                    if (!isJPGorPNG) {
                        that.$message({
                            message: '上传头像图片只能是 JPG/PNG 格式!',
                            type: 'warning'
                        })
                        return false;
                    }
                    // if (!isLt500K) {
                    //     that.$message({
                    //         message: '上传图片大小不能超过 500KB! 可压缩后上传',
                    //         type: 'warning'
                    //     })
                    //     return false;
                    // }
                    const formData = new FormData();
                    formData.append('file', file, file.name);
                    let oFileReader = new FileReader();
                    oFileReader.readAsDataURL(file);
                    oFileReader.onload = function (e) {
                        that.data.push({
                            Base64: e.target.result,
                            DataLength: file.size,
                            FileName: file.name
                        })
                    }
                },
            });
        }
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            tableData: [],
            headeData: [],
            imageDate: [],
            imageHeader: [],
            image: [],
            isTable: true,
            form: {
                page: 1,
                limit: 15,
            },
            form1: {
                page: 1,
                limit: 15,
            },
            loading: false,
            isBatch: false,
            success: 0,
            warning: 0,
            error: 0,
            multipleSelection: [],
            chack: {},//存放校验信息
        }
    },
    mixins:[importMixin],
    watch: {
        headeData() {
            const timer = setTimeout(() => {
                this.isTable = true;
                clearTimeout(timer)
            })
        }
    },
    computed: {
        value() {
            return function (str) {
                switch (str) {
                    case "brand":
                        return "品牌";
                    case "category":
                        return "类别";
                    case "classfiy":
                        return "分类";
                    case "item":
                        return "款型";
                    case "series":
                        return "系列";
                }
            }
        }
    },
    methods: {
        submitUpload(i = 0) {
            const that = this;
            if (i < this.tableData.length) {
                this.loading = true;
                if (i == 0) {
                    this.success = 0;
                    this.error = 0;
                    this.warning = 0;
                }
                if (this.tableData[i].isError) {
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!that.tableData[i]['规格编号']) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '规格编号不能为空';
                    this.submitUpload(i + 1);
                } else {
                    
                    let Article_Specifications_SerialNumber = that.tableData[i]['规格编号'];
                    $.ajax({
                        headers:requestHeaders(),
                        type: 'POST',
                        url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                        data: { 
                            Data: "business_article_specifications" ,
                            Condition: "Article_Specifications_SerialNumber='" + Article_Specifications_SerialNumber + "'"
                        },
                        success: function (data) {
                            console.log(data);
                            if (data.length == 1) {
                                if (that.tableData[i]['规格名称']) {
                                    data[0].Specifications_Name = that.tableData[i]['规格名称'];
                                }
                                if (that.tableData[i]['京东价格']) {
                                    data[0].JDCOM_Unit_Price = that.tableData[i]['京东价格'];
                                }
                                if (that.tableData[i]['京东链接']) {
                                    data[0].JDCOM_URL = that.tableData[i]['京东链接'];
                                }
                                let Article_SerialNumber = data[0].Article_SerialNumber;
                                $.ajax({
                                    headers:requestHeaders(),
                                    type: 'POST',
                                    url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                                    data: { 
                                        Data: "business_article_info" ,
                                        Condition: "Article_SerialNumber='" + Article_SerialNumber + "'"
                                    },
                                    success: function (data1) {

                                        if (data1.length == 1) {
                                            if (that.tableData[i]['商品名称']) {
                                                data1[0].Article_Name = that.tableData[i]['商品名称'];
                                            }
                                            if (that.tableData[i]['京东价格']) {
                                                data1[0].JDCOM_Unit_Price = that.tableData[i]['京东价格'];
                                            }
                                            if (that.tableData[i]['京东链接']) {
                                                data1[0].JDCOM_URL = that.tableData[i]['京东链接'];
                                            }
                                           
                                            let business_article_info = [{
                                                ...data[0],
                                                Children:{
                                                    business_article_specifications:[{
                                                        ...data1[0]
                                                    }]
                                                }
                                            }]
                                            data = {
                                                Data: JSON.stringify({
                                                    Modify: { business_article_info }
                                                })
                                            }
                                            that.submitForm(data, (res) => {//提交
                                                if (res.Status == 'success') {
                                                    that.tableData[i].isStatus = '1';
                                                    that.tableData[i].Cause = '',
                                                    that.success++;
                                                } else {
                                                    that.tableData[i].isStatus = '2';
                                                    that.tableData[i].Cause = '未知错误'
                                                    that.error++;
                                                }
                                                that.submitUpload(i + 1);
                                            })
                                        }
                                    },
                                    complete: function (XMLHttpRequest) {
                                        requestPretreatment(XMLHttpRequest);
                                    },
                                    dataType: "json"
                                });
                            }else{
                                that.tableData[i].isStatus = '2';
                                that.tableData[i].Cause = '没找到对应商品，检查规格编号是否正确';
                                that.error++;
                                that.submitUpload(i + 1);
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    });
                    
                }
            } else if (i != 0) {
                that.loading = false;
                that.$message({
                    message: "批量导入结束",
                    duration: 1000,
                    type: 'success'
                })
            } else {
                this.$message({
                    message: '请先导入模板后再上传',
                    duration: 1000,
                    type: 'warning'
                })
            }
        },
        submitForm(data, callback) {
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data,
                success: function (res) {
                    callback(res)
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var header = XLSX.utils.sheet_to_json(sheet, { header: 1 })[0];//获取
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。

                json.forEach(item => {
                    item.isEdit = false;
                    item.isStatus = '';
                    item.Cause = '';
                })
                that.isTable = false;
                that.headeData = header;
                that.tableData = json;
            }
        },
        handleSizeChange(val, id) {
            this[id].page = 1;
            this[id].limit = val;
        },
        handleCurrentChange(val, id) {
            this[id].page = val;
        },
        handleRemove(index, id) {//移除当前行
            this.$confirm('是否要删除此行?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                if (id == "form") {
                    this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
                } else if (id == 'form1') {
                    this.imageDate = this.imageDate.filter((i, id) => id != (this.form1.page - 1) * this.form1.limit + index)
                }

            }).catch(() => { });
        },
        handleClean() {//清空
            this.$confirm('是否要清空导入数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = [];
                this.imageDate = [];
            }).catch(() => { });
        },
    },
})